#include <QXmlStreamReader>
#include "standard-table-model.h"
#include "xml-reader.h"

XmlReader::XmlReader(QObject *parent) :
    QObject(parent), m_xml(0), m_model(0), m_headerFilled(false)
{
    m_recordNames << "Magazyn" << "Pracownik" << "Kontrahent"
                  << "Produkt" << "Zamowienie" << "Poz_zam" << "Prod_mag";
}

XmlReader::~XmlReader()
{
    delete m_xml;
}

QAbstractTableModel* XmlReader::convertToModel (QString message)
{
    if (m_model)
        delete m_model;
    if (m_xml)
        delete m_xml;

    m_xml = new QXmlStreamReader(message);
    if (m_xml->readNextStartElement())
    {
        if (m_xml->name() == "Odpowiedz")
        {
            m_model = new StandardTableModel(this);
            readAnswer();
        }
        else
        {
            m_xml->raiseError("Błędna nazwa odpowiedzi.");
            return 0;
        }
    }
    else
    {
        return 0;
    }
    return m_model;
}

void XmlReader::readAnswer()
{
    while (m_xml->readNextStartElement())
    {
        if (!m_model)
            return;

        if (isRecordName(m_xml->name().toString()))
            readRecord();
        else
        {
            m_xml->raiseError("Nieznana nazwa rekordu.");
            delete m_model;
            return;
        }
    }
}

void XmlReader::readRecord()
{
    m_fields.clear();
    while (m_xml->readNextStartElement())
    {
        if (!m_model)
            return;

        if (m_xml->name() == "metoda")
        {
            m_xml->skipCurrentElement();
            continue;
        }
        readField();
    }
    m_model->appendRow(m_fields);
    m_headerFilled = true;
}

void XmlReader::readField()
{
    if (!m_headerFilled)
    {
        m_model->setColumnCount(m_model->columnCount()+1);
        m_model->setHeaderData(m_model->columnCount()-1, Qt::Horizontal, m_xml->name().toString(), Qt::DisplayRole);
    }

    QString value = m_xml->readElementText();
    if (m_xml->error())
    {
        delete m_model;
        return;
    }
    m_fields.append(value);
}

bool XmlReader::isRecordName (QString name)
{
    return m_recordNames.contains(name);
}

QXmlStreamReader::Error XmlReader::error() const
{
    if (m_xml)
        return m_xml->error();
    else
        return QXmlStreamReader::NoError;
}

QString XmlReader::errorString() const
{
    if (m_xml)
        return m_xml->errorString();
    else
        return "";
}
